import React, { useState, useEffect, useRef } from 'react';
import { Space, Select, Card, Tooltip, Statistic, Typography, Modal, Table, Button, Form, Input, InputNumber, message } from "antd";
import { QuestionCircleFilled } from "@ant-design/icons";
import TheQueryForm from '@/components/TheQueryForm';
import TheButton from "@/components/TheButton";
import Json2Excel from '@/utils/Json2Excel.js';
import { storeAccountPrice, storeCashFlowCommissionPage, storeCashFlowCommissionList, storeAccountWithdrawData, storeAccountWithdrawCash } from '@/api/fundsManage/accountManage.js'
import { Decimal } from 'decimal.js';
const { Paragraph } = Typography;
const { TextArea } = Input

export default function ExtractApply() {
  const token = sessionStorage.getItem('RSnetToken')
  const FormRef = useRef()
  const searchOption = [
    {
      field: 'storeCashFlowCommissionId',
      label: '申请编号',
      placeholder: '申请编号',
      type: 'Input',
    },
    {
      field: 'payCode',
      label: '流水编号',
      placeholder: '流水编号',
      type: 'Input',
    },
    {
      field: 'auditState',
      label: '申请状态',
      placeholder: '全部',
      type: 'Select',
      options: [
        { value: '', label: '全部' },
        { value: 0, label: '待审核' },
        { value: 1, label: '通过' },
        { value: 3, label: '驳回' }
      ],
    },
    {
      field: 'payState',
      label: '提现状态',
      placeholder: '全部',
      type: 'Select',
      options: [
        { value: '', label: '全部' },
        { value: 0, label: '提现中' },
        { value: 1, label: '成功' },
        { value: 2, label: '失败' }
      ],
    },
    { field: 'time', label: '申请日期', type: 'RangePicker' }
  ]//搜索
  const [queryForm, setQueryForm] = useState(null) //搜索值
  const columns = [
    {
      title: "申请编号",
      dataIndex: "storeCashFlowCommissionId",
      key: "storeCashFlowCommissionId",
    },
    {
      title: "类型",
      dataIndex: "businessType",
      key: "businessType",
      render(text) {
        return text === 2 && '提现'
      }
    },
    {
      title: "金额(元)",
      dataIndex: "price",
      key: "price",
      render: (text) => {
        return Decimal(text).div(Decimal(100)).toNumber().toFixed(2)
      }
    },
    {
      title: "申请状态",
      dataIndex: "auditState",
      key: "auditState",
      render(text, record) {
        let label = ''
        switch (text) {
          case 0:
            label = '待审核'
            break
          case 1:
            label = '通过'
            break
          case 2:
            label = '通过 '
            break
          case 3:
            label = (
              <div >
                <span style={{ marginRight: 5 }}>驳回</span>
                <Tooltip title={record.rejectReason}>
                  <QuestionCircleFilled />
                </Tooltip>
              </div>
            )
            break
        }
        return label
      }
    },
    {
      title: "申请时间",
      dataIndex: "applyTime",
      key: "applyTime",
    },
    {
      title: "备注",
      dataIndex: "remark",
      key: "remark",
    },
    {
      title: "提现状态",
      dataIndex: "payState",
      key: "payState",
      render(text, record) {
        let label = ''
        switch (text) {
          case 0:
            label = '提现中'
            break
          case 1:
            label = '成功'
            break
          case 2:
            label = <div >
              <span style={{ marginRight: 5 }}>失败</span>
              <Tooltip title={record.failReason}>
                <QuestionCircleFilled />
              </Tooltip>
            </div>

            break
          default:
            label = '-'
        }
        return label
      }
    },
    {
      title: "流水编号",
      dataIndex: "payCode",
      key: "payCode",
    },
  ] //表头
  const [dataSource, setDataSource] = useState([]); // 表格数据
  const [pageData, setPageData] = useState({ pageNo: 1, pageSize: 10, total: 1 })
  const [exportLoading, setExportLoading] = useState(false); // 导出loading
  const [isWithdrawModalOpen, setIsWithdrawModalOpen] = useState(false); // 提现申请弹窗
  const [maxMoney, setMaxMoney] = useState() //最大提现金额
  const [withdrawMoney, setWithdrawMoney] = useState() //已提现金额
  const [canWithdrawMoney, setCanWithdrawMoney] = useState() //可提现金额
  const [waitSettledPrice, setWaitSettledPrice] = useState() //待结算金额

  useEffect(() => {
    getData({ pageNo: pageData.pageNo, pageSize: pageData.pageSize })
    getAmountSummary()
  }, [])
  // 获取商检金额汇总数据
  const getAmountSummary = async () => {
    storeAccountPrice({ token }).then(res => {
      if (res.code === 0) {

        setWithdrawMoney(Decimal(res.data.withdrawPrice).div(Decimal(100)).toNumber().toFixed(2))
        setCanWithdrawMoney(Decimal(res.data.canWithdrawPrice).div(Decimal(100)).toNumber().toFixed(2))
        setWaitSettledPrice(Decimal(res.data.waitSettledPrice).div(Decimal(100)).toNumber().toFixed(2))
      }
    })
  }
  // 获取表格数据
  const getData = async (value) => {
    if (value && value.hasOwnProperty('time')) {
      value.applyBeginTime = value.time[0].format('YYYY-MM-DD') + ' 00:00:00'
      value.applyEndTime = value.time[1].format('YYYY-MM-DD') + ' 23:59:59'
      delete value.time
    }
    storeCashFlowCommissionPage({
      businessType: 2,
      ...value,
      token
    }).then(res => {
      if (res.code === 0 && res.data) {
        setDataSource(res.data)
        setPageData({ pageNo: res.pageNo, pageSize: res.pageSize, total: res.totalCount })
      }
    })
  }
  // 分页切换
  const pageChange = async (pageNo, pageSize) => {
    await getData({
      pageNo,
      pageSize,
      ...queryForm
    })
  }
  // 搜索
  const onFormSearch = (value) => {
    getData({ ...value, pageNo: 1, pageSize: 10 }).then(res => {
      setQueryForm({ ...value })
    })
  }
  // 搜索重置
  const onReset = () => {
    setQueryForm(null)
    getData({ pageNo: 1, pageSize: 10 })
  }
  // 导出
  const exportGoods = () => {
    if (queryForm === null) {
      return Modal.warning({ title: '提醒', content: '请选择筛选条件并查询后再导出对应的订单，暂不支持全量导出。', });
    }
    setExportLoading(true)
    storeCashFlowCommissionList({ ...queryForm, businessType: 2, token }).then(res => {
      if (res.code === 0) {
        let data = []
        res.data.forEach(item => {
          let { auditState, payState } = ''
          //审核状态
          switch (item.auditState) {
            case 0:
              auditState = '待审核'
              break
            case 1:
              auditState = '通过'
              break
            case 2:
              auditState = '通过 '
              break
            case 3:
              auditState = '驳回'
              break
          }
          //提现状态
          switch (item.payState) {
            case 0:
              payState = '提现中'
              break
            case 1:
              payState = '成功'
              break
            case 2:
              payState = '失败 '
              break
            default: '-'
          }
          data.push({
            ...item,
            auditState,
            payState,
            businessType: item.businessType === 2 && '提现',
            price: Decimal(item.price).div(Decimal(100)).toNumber().toFixed(2)
          })
        })
        const option = {
          fileName: '商家资金流水明细',
          header: [
            {
              prop: "storeCashFlowCommissionId",
              title: '申请编号',
              width: 25,
            },
            {
              prop: "businessType",
              title: '类型',
            },
            {
              prop: "price",
              title: '金额(元)',
            },
            {
              prop: "auditState",
              title: '申请状态',
            },
            {
              prop: "applyTime",
              title: '申请时间',
              width: 25
            },
            {
              prop: "remark",
              title: '备注',
            },
            {
              prop: "payState",
              title: '提现状态',
            },
            {
              prop: "payCode",
              title: '流水编号',
              width: 25
            }
          ],
          dataSource: data
        }
        Json2Excel(option)
        setExportLoading(false)
      } else {
        message.info('导出失败请重试');
        setExportLoading(false)
      }
    })

  }
  // 申请提现
  const withdraw = async () => {
    await storeAccountWithdrawData().then(res => {
      if (res.code === 0) {
        setMaxMoney(Decimal(res.data.maxWithdrawSinglePrice).div(Decimal(100)).toNumber().toFixed(2))
        if (res.data.storeTodayWithdrawCount >= res.data.maxWithdrawCount) {
          Modal.warning({
            title: '提醒',
            content: (<div>  {`今日已达到提现次数的上限：${res.data.maxWithdrawCount}次。`}<br />  请明天再尝试提现~  </div>)
          });
        } else {
          setIsWithdrawModalOpen(true)
        }
      }
    })

  }
  // 确认申请提现
  const submitWithdraw = () => {
    FormRef.current.validateFields().then(async (value) => {
      // console.log(value, 'dddddddd');
      storeAccountWithdrawCash({ ...value, withdrawPrice: Decimal(value.withdrawPrice).mul(100).toNumber() }).then(res => {
        if (res.code === 0) {
          message.success('提现申请成功');
          cancelWithdraw()
          getAmountSummary()
          pageChange(1, 10)
        }
      })
    })
  }
  // 取消申请提现
  const cancelWithdraw = () => {
    FormRef.current.resetFields()
    setIsWithdrawModalOpen(false)
  }
  return (
    <div className='wrap-box wrap-box-content'>
      <Paragraph strong style={{ margin: 0, fontSize: 20 }}>
        <blockquote>商家账户金额汇总</blockquote>
      </Paragraph>
      <Space>
        <Card
          style={{ width: 300 }}
          title="已提现金额"
          extra={<Tooltip title="累计提现的金额">  <QuestionCircleFilled style={{ fontSize: 20 }} /> </Tooltip>}
        >
          <Statistic prefix={"￥"} value={withdrawMoney} precision={2} />
        </Card>
        <Card
          style={{ width: 300 }}
          title="可提现金额"
          extra={
            <Tooltip title="可提现金额=订单中状态为已结算的实付金额之和 - 已提现金额-提现中的金额">
              <QuestionCircleFilled style={{ fontSize: 20 }} />
            </Tooltip>
          }
        >
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
            <Statistic prefix={"￥"} value={canWithdrawMoney} precision={2} />
            {canWithdrawMoney > 0 && <TheButton type="link" haspermi={['fundsManage:accountManage:payouts']} onClick={withdraw}>  提现 </TheButton>}
          </div>

        </Card>
        <Card
          style={{ width: 300 }}
          title="待结算金额"
          extra={
            <Tooltip title="待结算金额=订单中状态为“ 待分享、待发货、待收货、交易完成” 的金额之和">
              <QuestionCircleFilled style={{ fontSize: 20 }} />
            </Tooltip>
          }
        >
          <Statistic prefix={"￥"} value={waitSettledPrice} precision={2} />
        </Card>
      </Space>
      <Paragraph strong style={{ margin: 0, fontSize: 20 }}>
        <blockquote>商家资金流水明细</blockquote>
      </Paragraph>
      <TheQueryForm option={searchOption} show onGetValues={(values) => onFormSearch(values)}
        onReset={(values) => onReset(values)}>
        <TheButton style={{ marginLeft: 20 }} haspermi={['fundsManage:accountManage:export']} onClick={exportGoods} loading={exportLoading}>导出</TheButton>
      </TheQueryForm>
      <Table
        bordered
        columns={columns}
        dataSource={dataSource}
        rowKey={'storeCashFlowCommissionId'}
        pagination={{
          position: ['bottomCenter'],
          current: pageData.pageNo,
          pageSize: pageData.pageSize,
          total: pageData.total,
          showSizeChanger: false,
          onChange: pageChange
        }}
      />
      <Modal title="提现申请" open={isWithdrawModalOpen} onOk={submitWithdraw} onCancel={cancelWithdraw} okText='提现'>
        <Form ref={FormRef} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
          <Form.Item
            label="提现金额"
            name="withdrawPrice"
            rules={[{ required: true, message: `请输入0.1~${canWithdrawMoney}之间的数字` }]}
            extra={`单笔提现超过¥${maxMoney}，将需要人工审核后方可到账，预计审核时间1~3个工作日`}
          >
            <InputNumber style={{ width: '40%' }} controls={false} max={canWithdrawMoney} min={0.1} addonAfter="元" precision={2} />
          </Form.Item>
          <Form.Item
            label="备注"
            name="remark"
          >
            <textarea id='myTextarea' maxLength={300} style={{ height: 150, width: '100%', borderColor: '#d9d9d9', resize: 'none', outline: 'none' }} ></textarea>
          </Form.Item>
        </Form>
      </Modal>
    </div >
  )
}